var app = getApp();
const date_util = require('../../utils/date_util.js')
var util = require('../../utils/util.js')
var api = require('../../config/api.js')
var version = require('../../config/version.js')
var base64 = require('../../utils/base64.js')
var event = require('../../utils/event.js');
const qiniuUploader = require("../../utils/qiniuUploader");
const logger = wx.getLogManager({
  level: 1
})
const uploadcontroll = require("../../utils/UploadControll.js")
const promisify = require("../../utils/promisify.js")
const upload = promisify(uploadcontroll.upload)
const navigationBarHeight = (getApp().statusBarHeight + 44) + 'px'

Page({
  data: {
    navigationBarTitle: '',
    navigationBarHeight,
    platform: app.globalData.platform,
    photos: [],
    videopath: '',
    uploadType: 'TEXT',
    tonggan: '',
    qiniuToken: '',
    item: null,
    userInfo: app.globalData.userInfo,
    focus: false,
    emojiValue: '',
    // 视频
    videoContext: null,
    isPlay: true,
    swiperCurrentIndex: 0
  },

  onLoad: function(options) {
    var that = this
    let dataEncode = options.dataObj
    let dataDecode = decodeURIComponent(dataEncode)
    let item = JSON.parse(base64.decode(dataDecode))

    item.acti_photo = item.coverUrl

    event.on('UploadChanged', self, this.onUploadChanged);

    if (that.data.auth && that.data.hasPhone) {
      that.getQiniuToken();
    } else {
      //else
      that.auth = that.selectComponent("#auth");
      util.getScope('scope.userInfo').then(function(resss) {
        if (resss) {
          that.auth.hideAuth();
          ///防止緩存失效带来的问题
          let code = null;
          return that.login().then((res) => { //userInfo
            code = res.code;
            wx.getUserInfo({
              withCredentials: true,
              success: function(res_user) {
                //先去登陆        
                wx.request({
                  url: api.userAuth,
                  data: {
                    platform: 'wx',
                    authorizationCode: code,
                    userEncryptrfData: res_user.encryptedData,
                    iv: res_user.iv
                  },
                  method: 'POST',
                  header: {
                    'Content-Type': 'application/json',
                    'accessToken': wx.getStorageSync('token'),
                    'appVersion': version.appVersion,
                    'deviceModel': getApp().globalData.systemInfo.model,
                    'platform': 'wx',
                    'build': version.build,
                    'deviceMachineCode': '',
                    'deviceOS': getApp().globalData.systemInfo.system.split(" ")[0],
                    'deviceOSVersion': getApp().globalData.systemInfo.system,
                  },

                  success: function(res) {
                    if (res && res.statusCode == 200 && res.data.code == 200) {
                      wx.setStorageSync('token', res.data.data.token);
                      app.globalData.token = res.data.data.token;
                      var userInfo = res.data.data.user
                      if (userInfo && !userInfo.avatarUrl) {
                        userInfo.avatarUrl = version.defaultAvataUrl
                      }
                      wx.setStorageSync('userInfo', userInfo);
                      app.globalData.userInfo = userInfo
                      app.globalData.hasUserInfo = true
                      app.globalData.auth = true
                      wx.setStorageSync('auth', true);
                      that.setData({
                        item: item,
                        userInfo: app.globalData.userInfo
                      });
                      that.getQiniuToken();
                    }
                    if (res && res.data.code == 301) {
                      wx.setStorageSync('token', res.data.data.token);
                      app.globalData.token = res.data.data.token;
                      app.globalData.hasPhone = false
                      wx.setStorageSync('hasPhone', false);
                      that.setData({
                        hasPhone: false,
                        isFocus: false,
                      });
                      that.auth.showAuth();
                    }
                  }
                })
              }
            })
          })
          //防止緩存失效带来的问题
        } else {
          that.setData({
            item: item
          });
          that.auth.showAuth();
        }
      })
      //else
    }
    wx.hideShareMenu();
  },
  login: function() {
    return new Promise(function(resolve, reject) {
      wx.login({
        success: function(res) {
          if (res.code) {
            //登录远程服务器
            resolve(res);
          } else {
            reject(res);
          }
        },
        fail: function(err) {
          reject(err);
        }
      });
    });
  },

  onMyevent: function(e) {
    var that = this
    that.setData({
      userInfo: e.detail.paramBtoA.userInfo
    })
    if (that.data.userInfo && JSON.stringify(userInfoValue) != "{}") {
      that.getQiniuToken();
    }
  },

  onReady: function() {
    this.setData({
      keyboard: this.selectComponent('#keyboard'),
      isFocus: true,
    });
    this.data.keyboard.showKeyboard();
    this.videoContext = wx.createVideoContext('myVideo')
  },
  onShow: function() {},

  onHide: function() {},

  onUnload: function() {
    event.remove('UploadChanged', self, this.onUploadChanged);
  },

  onUploadChanged: function(res) {
    var that = this
    var uploadType = that.data.uploadType
    if (uploadType == 'IMAGE') {
      var allProcess = 0
      let photos_temp = that.data.photos
      let photos_update = photos_temp.map(function(value, index, array) {
        if (value.size == (res.totalBytesExpectedToSend - 1270)) {
          value.progress = res.progress
          allProcess += value.progress
          return value
        } else {
          allProcess += value.progress
          return value
        }
      })
      console.log(photos_update)
      wx.showLoading({
        title: '已经上传' + Math.ceil(allProcess / photos_update.length) + '%',
        mask: true
      })

      that.setData({
        photos: photos_update
      })
    }

    if (uploadType == 'VIDEO') {
      wx.showLoading({
        title: '已经上传' + res.progress + '%',
        mask: true
      })
    }
  },

  goSearch: function() {
    var that = this;
    wx.navigateBack({
      delta: 1
    })
  },
  selectPhoto: function() {
    var that = this
    wx.chooseImage({
      count: 6, // 默认9 compressed original
      sizeType: ['compressed'],
      sourceType: ['album'],
      success: function(res) {
        console.log(res)
        var tempFilePaths = res.tempFilePaths
        var photosJsonArray = tempFilePaths.map(function(val, index) {
          var t = {}
          t.id = index
          t.path = val
          t.progress = 0
          t.size = val.size
          return t;
        });
        that.setData({
          videopath: '',
          photos: photosJsonArray,
          uploadType: 'IMAGE'
        })
      }
    })
  },

  selectPhotoNew: function() {
    var that = this

    var iscompress = that.data.platform == 'ios' ? 'compressed' : 'original'
    logger.info('1.刚点击选择图片按钮：', iscompress)
    wx.chooseImage({
      count: 6, // 默认9 compressed original
      sizeType: [iscompress],
      sourceType: ['album'],
      success: function(res) {
        logger.info('2.选择手机相册的图片成功之后：', res)
        var tempFiles = res.tempFiles
        var all = []
        var photosJsonArray = tempFiles.map(function(val, index) {
          if (val.size <= 2000000) {
            var t = {}
            t.id = index
            t.path = val.path
            t.progress = 0
            t.size = val.size
            return t;
          } else {
            all.push(index + 1);
          }
          logger.info('3.循环获取图片数组：', index, val)
        });
        logger.info('4.循环获取图片数组成功之后:', photosJsonArray)
        photosJsonArray = photosJsonArray.filter(item => item != null);
        logger.info('5.图片路径数组去空null过滤之后:', photosJsonArray)
        if (all.length > 0) {
          let str = all.join(',');
          logger.info('6.拼接移除的图片索引', all, str)
          wx.showToast({
            title: '第' + str + '张图片均大于2M,已被移除,请重新上传!',
            icon: 'none'
          })
        }
        that.setData({
          videopath: '',
          photos: photosJsonArray,
          uploadType: 'IMAGE',
          swiperCurrentIndex: 0
        })
      }
    })

  },

  delPhoto: function(e) {
    var that = this
    var index = e.currentTarget.dataset.index
    var photo = that.data.photos
    photo.splice(index, 1)
    logger.info('12.删除图片后：', photo, index)
    if (photo.length == index) {
      // 判断用户删除的图片是不是图片数组内的最后一张，是则将swiper的current值为图片数组长度减一，可以保证显示上一张图片
      console.log('执行最后一张');
      that.setData({
        photos: photo,
        swiperCurrentIndex: that.data.photos.length - 1
      })
    } else {
      // 删除的图片不是图片数组内的最后一张，这样可以保证当前显示下一张图片
      console.error('删除的图片不是图片数组内的最后一张');
      that.setData({
        photos: photo
      })
    }
  },
  goSettingCurrentIndex: function(e) {
    let that = this;
    console.log(e.detail.current)
    that.setData({
      swiperCurrentIndex: e.detail.current
    })
  },
  selectVideo: function() {
    var that = this
    var iscompress = that.data.platform == 'ios' ? true : false
    logger.info('7.刚点击选择视频按钮：', iscompress)
    wx.chooseVideo({
      compressed: iscompress,
      sourceType: ['album'],
      maxDuration: 20,
      success: function(res) {
        logger.info('8.选择手机视频成功之后:', res)
        var tempFilePath = res.tempFilePath
        if (res.duration > 20) {
          logger.info('9.视频大于20秒：', res.duration)
          wx.showModal({
            title: '视频过长',
            showCancel: false,
            content: '您上传的视频超过20秒！'
          })
        } else if (res.size > 25 * 1024 * 1024) {
          logger.info('10.视频大于25M：', res.size)
          wx.showModal({
            title: '视频过大',
            showCancel: false,
            content: '请上传小于25M的视频文件,您当前要上传的视频大小为' + (res.size / (1024 * 1024)).toFixed(2) + "M"
          })

        } else {
          logger.info('11.视频合格：', tempFilePath)
          that.setData({
            photos: [],
            videopath: tempFilePath,
            uploadType: 'VIDEO'
          })
        }

      }
    })
  },

  //感受框
  tongganInput: function(e) {
    this.setData({
      tonggan: e.detail.value
    })
  },
  onFocus: function(e) {
    this.setData({
      focus: true,
      isFocus: false,
    })
    this.data.keyboard.hideKeyboard();
  },
  offFocus: function(e) {
    this.setData({
      focus: false
    })
  },

  // Emoji框

  emojiInput: function(e) {
    // this.setData({
    //   emojiValue: e.detail.value
    // })
  },
  onEmojiFocus: function(e) {
    this.setData({
      focus: true
    })
    this.data.keyboard.showKeyboard();
  },
  offEmojiFocus: function(e) {
    this.setData({
      focus: false
    })
    this.data.keyboard.hideKeyboard();
  },

  pubTonggan: function() {
    var that = this
    var sendPhotos = ''
    var sendVideo = ''
    var item = that.data.item
    var photos = that.data.photos
    var tonggan = that.data.tonggan
    var videopath = that.data.videopath
    var uploadType = that.data.uploadType

    if (that.data.tonggan == '' && photos.length == 0 && that.data.videopath == '') {
      wx.showModal({
        title: '感受为空',
        showCancel: false,
        content: '要记得写感受和上传现场图片、视频哦!'
      })
      return
    }
    if (util.judgeChartCount(tonggan) >= 2000) {
      wx.showModal({
        title: '感受过长',
        showCancel: false,
        content: '感受字数有点多,不如拆分为几条发布!'
      })
      return
    }
    if (photos.length > 0 && uploadType == 'IMAGE') {  //插入图片
      logger.info('类型:插入图片', photos)
      that.uploadMultiImage(photos, uploadType, that.data.qiniuToken)
    }
    if (videopath != '' && photos.length == 0 && uploadType == 'VIDEO') { //视频
      logger.info('类型:插入视频', videopath)
      var videoArr = videopath.split(',')
      logger.info('待插入的视频数组', videoArr)
      that.uploadMultiImage(videoArr, uploadType, that.data.qiniuToken)
    }
    if (photos.length == 0 && videopath == '' && tonggan != '') { //纯文字
      if (util.judgeChartCount(tonggan) >= 20) {
        logger.info('类型:插入文字', tonggan)
        that.insertPicVideo(item.id, tonggan, 'TEXT', '', that.data.emojiValue)
      } else {
        wx.showModal({
          title: '感受过短',
          showCancel: false,
          content: '您发表的感受少于20个字符,再表达点嘛！'
        })
      }
    }
  },

  // 键盘事件
  /**
   * 显示键盘，同时设置虚拟输入框为激活状态
   */
  showKeyboard: function() {
    this.setData({
      isFocus: true
    })
    this.data.keyboard.showKeyboard();
  },

  /**
   * 隐藏键盘，同时设置虚拟输入框为未激活状态
   */
  hideKeyboard: function(e) {
    this.setData({
      isFocus: false
    });
    this.data.keyboard.hideKeyboard();
  },

  /**
   * 配合键盘输入事件：input，获取输入内容到虚拟输入框中
   */
  inputChange: function(e) {
    var textValue = e.detail;
    console.log(textValue)
    let allEmoji = ''
    allEmoji = textValue.join('');
    if (textValue.length > 0) {
      allEmoji = textValue.join('');
    }
    this.setData({
      emojiValue: allEmoji
    });
  },

  /**
   * 配合键盘点击‘完成’事件：done，设置虚拟输入框为未激活状态
   */
  inputDone: function() {
    this.setData({
      isFocus: false
    })
  },

  // 获取七牛token
  getQiniuToken: function() {
    var that = this
    util.pututrequest(api.qiniutoken, 'GET').then((res) => {
      if (res && res.code == 200) {
        that.setData({
          qiniuToken: res.data.uploadToken
        })
      } else {
        console.log('初始化失败原因：')
        console.log(res)
        logger.info('失败:获取七牛token！', res)
        wx.showLoading({
          title: '初始化失败...',
        })
        setTimeout(() => {
          wx.hideLoading();
          wx.navigateBack({
            delta: 1
          })
        }, 1000);
      }
    })
  },

  // 上传 图片和视频 到 七牛
  uploadMultiImage: function(paths, uploadType, qiniutoken) {
    let z = this
    var item = z.data.item
    var tonggan = z.data.tonggan
    var emoji = z.data.emojiValue
    let url = 'https://up-z1.qbox.me'
    const promises = paths.map(function(value, index, array) {
      if (uploadType == 'IMAGE') {
        return upload({
          url: url,
          path: value.path,
          name: 'file',
          extra: {
            token: qiniutoken,
            'x:uid': 'WX' + new Date().getTime(),
          },
          progress: index,
          size: array.length,
          uploadType: uploadType
        })
      }

      if (uploadType == 'VIDEO') {
        return upload({
          url: url,
          path: value,
          name: 'file',
          extra: {
            token: qiniutoken
          },
          progress: index,
          size: array.length
        })
      }

    })

    wx.showLoading({
      title: '正在上传...',
    })

    Promise.all(promises).then(function(datas) {
      //所有上传完成后
      logger.info('所有promises:', promises)
      logger.info('所有上传的promise完成且返回：:', datas)
      wx.hideLoading()
      // 服务器返回的路径
      let paths = datas.map(data => {
        let t = {}
        t.key = data.data.key
        t.uid = data.data.uid
        return t
      })
      //正式插入数据库
      paths.sort(z.compare("uid"));
      let photoArr = paths.map(data => {
        return data.key
      })
      var sendPhotos = photoArr.join(',')
      z.insertPicVideo(item.id, tonggan, uploadType, sendPhotos, emoji)

    }).catch(function(ress) {
      logger.info('上传失败:', ress)
      wx.hideLoading()
      // util.handleFail(res)  出错逻辑控制
    })

  },
  //上传七牛结束

  //插入数据库
  insertPicVideo: function(activityId, content, type, extra_data, emotion) {
    var that = this
    util.pututrequest(api.uploadTonggan, 'POST', {
      activityId: encodeURIComponent(activityId),
      content: content,
      type: type,
      keys: extra_data,
      emotion: emotion
    }).then((res) => {
      if (res && res.code == 200) {
        wx.hideLoading()
        wx.showToast({
          title: '发布成功',
          icon: 'success',
          duration: 2000
        })
        console.log('发布成功')
        wx.navigateTo({
          url: '/pages/detail/detail?uuid=' + activityId + '&source=upload&commId=0&type=1',
          success: function() {},
          fail: function() {},
          complete: function() {}
        })

        that.setData({
          photos: [],
          tonggan: '',
          videopath: '',
          uploadType: '',
          emojiValue: ''
        })

      } else {
        logger.info('失败:最后一步插入数据库！', res)
        wx.showToast({
          title: '发布失败',
          icon: 'loading',
          duration: 2000
        })
      }
    })

  },
  //插入数据库
  // 定义属性比较器
  compare: function(propertyName) {
    return function(object1, object2) {
      var value1 = object1[propertyName];
      var value2 = object2[propertyName];
      if (value2 > value1) {
        return -1;
      } else if (value2 < value1) {
        return 1;
      } else {
        return 0;
      }
    }
  },

})